package com.hfjava.herundong.controller;

import com.hfjava.herundong.dao.ToDoDao;
import com.hfjava.herundong.entity.ToDo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Date;

@RestController
public class IndexController  {
    @Autowired
    ToDoDao toDoDao;
    //获取素材列表id
    public static void main(String[] args) throws IOException {
        URL url =new URL("https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=24_xgxvHJvsK_kYptFdWi550RSVJfoazchsh3xH5VyxDEeDVHfXW1ckj8ljfYNE6P2yH946B3c5tEuPVzjQCSAeF_HmPe3ZiF96AB1oCwazyojbfW4DWdCxcEOoTKoHDTfAGACYO");
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setDoOutput(true);
        con.setDoInput(true);

        String sendStr ="{\"type\":\"voice\",\"offset\":0,\"count\":1}";
        con.getOutputStream().write(sendStr.getBytes());
        con.getOutputStream().flush();

        BufferedReader br = new BufferedReader(
                new InputStreamReader(con.getInputStream(), "utf-8")
        );

        String str;
        StringBuffer sb = new StringBuffer();

        while ((str = br.readLine()) != null) {
            sb.append(str);
        }

        System.out.println(sb);
    }

    @PostMapping("/index")
    public String name(HttpServletRequest req) throws IOException {
        BufferedReader br = new BufferedReader(
                new InputStreamReader(req.getInputStream(), "utf-8")
        );

        String str;
        StringBuffer sb = new StringBuffer();

        while ((str = br.readLine()) != null) {
            sb.append(str);
        }

        br.close();

        String xml = sb.toString();
        int start =xml.indexOf("CDATA[");
        int end =xml.indexOf("]",start);
        String toUserName = xml.substring(start+6,end);
        System.out.println(toUserName);

        start =xml.indexOf("CDATA[",end);
        end =xml.indexOf("]",start);
        String fromUserName = xml.substring(start+6,end);
        System.out.println(fromUserName);

        Date date =new Date();
        String time =(date.getTime()/1000+"");
        //String media_id ="iYBMciEKh6Y05_MWxD4vgQ8BObx3uFG5ZVafNDGDfv4";
        return "<xml>\n" +
                "  <ToUserName><![CDATA["+fromUserName+"]]></ToUserName>\n" +
                "  <FromUserName><![CDATA["+toUserName+"]]></FromUserName>\n" +
                "  <CreateTime>"+time+"</CreateTime>\n" +
                "  <MsgType><![CDATA[text]]></MsgType>\n" +
                "  <Content><![CDATA[你好厉害！！]]></Content>\n" +
                "</xml>";
        /*return "<xml>\n" +
                "  <ToUserName><![CDATA["+fromUserName+"]]></ToUserName>\n" +
                "  <FromUserName><![CDATA["+toUserName+"]]></FromUserName>\n" +
                "  <CreateTime>"+time+"</CreateTime>\n" +
                "  <MsgType><![CDATA[voice]]></MsgType>\n" +
                "  <Voice>\n" +
                "    <MediaId><![CDATA["+media_id+"]]></MediaId>\n" +
                "  </Voice>\n" +
                "</xml>";*/
    }

    @GetMapping("/index")
    public String name(String signature, String timestamp, String nonce, String echostr) {

        System.out.println(signature);
        System.out.println(timestamp);
        System.out.println(nonce);
        System.out.println(echostr);
        String[] strs = {"hehe", timestamp, nonce};
        Arrays.sort(strs);

        StringBuilder str = new StringBuilder();
        for (int i = 0; i < strs.length; i++) {
            str.append(strs[i]);
        }

        MessageDigest md = null;
        String tempStr = null;
        try {
            md = MessageDigest.getInstance("SHA-1");
            byte[] digest = md.digest(str.toString().getBytes());
            tempStr = byteToStr(digest);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        if (signature.toUpperCase().equals(tempStr)) {
            return echostr;
        }

        return "";
    }

    private String byteToStr(byte[] byteArray) {
        String strDigest = "";
        for (int i = 0; i < byteArray.length; i++) {
            strDigest = strDigest + byteToHexStr(byteArray[i]);
        }
        return strDigest;
    }

    private String byteToHexStr(byte b) {
        char[] digit = {
                '0',
                '1', '2', '3', '4', '5', '6', '7',
                '8', '9', 'A', 'B', 'C', 'D', 'E',
                'F'};
        char[] tempArr = new char[2];
        tempArr[0] = digit[(b >>> 4 & 0xF)];
        tempArr[1] = digit[(b & 0xF)];
        String s = new String(tempArr);
        return s;
    }

    @GetMapping("/add")
    public String addNewUser(@RequestParam String name,
                             @RequestParam String content) {
        ToDo t = new ToDo();
        t.setContent(content);
        t.setCreatedate(new Date() + "");
        t.setName(name);
        toDoDao.save(t);
        return "Saved";
    }

    @GetMapping("/all")
    public @ResponseBody
    Iterable<ToDo> getAllUsers() {
        return toDoDao.findAll();
    }
}
